<template>
  <div>
    <div class="AllCont">
      <div class="contAllThree transTopCont">
        <div class="mobileCont" ref="claims">
          <div class="AllOne" :class="[{ mobileContActive: isMobileCont }]">
            <div class="newChatBtn" @click="openMobileMode">查看历史对话</div>
            <div class="historyTime">当前对话：{{ timeListStr }}</div>
          </div>
        </div>
        <div :class="[{ mobileMode: isActive }]" class="AllOne timeRol" :style="{ height: screenHeightBg }">
          <div class="newChatBtn" @click="addNews">添加新对话</div>
          <div class="timeList">
            <div
              v-for="(item, index) in timeListLeft"
              :key="index"
              :class="['listOrder', index === timeIndex ? 'active' : '']"
              @click.stop="choseTime(item, index)"
            >
              <img class="session-logo" src="@assets/chat/xinxi.png" alt="" />
              <div class="session-name" v-if="index !== timeIndex || iconShow">{{ item.name }}</div>
              <a-input v-if="index === timeIndex && !iconShow" v-model="editTime" placeholder="请填写备注"></a-input>
              <div class="space" v-if="index === timeIndex && iconShow">
                <i class="iconfont icon-bianji" @click.stop="editIcon(item)"></i>
                <a-popconfirm title="确定删除吗?" @confirm="() => deleteTime(item, index)">
                  <i class="iconfont icon-shanchu"></i>
                </a-popconfirm>
              </div>
              <div class="space" v-if="index === timeIndex && !iconShow">
                <a-popconfirm title="确定修改吗?" @confirm="() => edit(item, index)">
                  <i class="iconfont icon--zhengque"></i>
                </a-popconfirm>
                <i class="iconfont icon--cuowu" @click.stop="closeEdit"></i>
              </div>
              <input class="iconfont" type="radio" v-model="timeIndex" name="sex" :value="index" />
              <!-- <j-date v-model="formData.jDate" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"/> -->
            </div>
          </div>
          <div class="closeMode" @click="isActive = false"><div class="closeBtn">关闭</div></div>
        </div>
        <div class="AllOne transWidth">

          <div class="timeList">
            <trans-late ref="modalPlanCent" :model="model" @appApiAsk="appApiAsk" v-if="workPlanNum === '5'"></trans-late>
            <div class="justify-between">
              <div class="sheCot copyTrans" @click="generatedBtn" v-if="loadingShow">立即翻译</div>
              <div class="sheCot copy" v-else>
                正在加载中
                <div class="loading"></div>
              </div>
            </div>
            <div class="transCont">
              <div class="transLeft">
                <a-textarea :rows="21" v-model="model.content" placeholder="请输入内容。。。" />  
              </div> 
              <div class="transMid">
                <i class="iconfont icon-xinyonghucha"></i>
              </div>
              <div class="transRight">
                <div class="transHtml" v-html="textareaTo(model.answer)" v-if="loadingShow"></div>
                <div class="transHtml load" v-else>正在翻译中...<div class="loading"></div></div>
              </div>
            </div>
          </div>
          <div class="justify-between topBomFix">
              <div class="sheCot copyTrans" @click="generatedBtn" v-if="loadingShow">立即翻译</div>
              <div class="sheCot copy" v-else>
                正在加载中
                <div class="loading"></div>
              </div>
          </div>
        </div>
      </div>
    </div>

    <member-model ref="modalMember" v-if="memberShow"></member-model>
    <div class="moveUpDown" @click.stop="scrollUp"><img src="@assets/down.png" alt="" /></div>
  </div>
</template>

<script>
// import IndexChart from './IndexChart'
// import IndexTask from "./IndexTask"
// import IndexBdc from './IndexBdc'
import { mapGetters } from 'vuex'
import { sessionNoteList } from '@/api/api'
import { deleteAction } from '@/api/manage'
import TransLate from './modules/TransLate' //翻译
import MemberModel from '../component/MemberModel' //付费跳转弹框
export default {
  name: 'WorkPlan',
  components: {
    TransLate,
    MemberModel,
  },
  data() {
    return {
      model: {},
      isActive: false,
      memberShow:false,
      iconShow: true,
      loadingShow: true,
      confirmLoading: false,
      isMobileCont: false,
      acquisitionTime: '',
      workPlanNum:'1',
      editTime: '',
      screenWidth: '',
      screenHeight: '',
      screenHeightBg: '',
      timeIndex: 0,
      sessionTypeId: '',
      formData: {
        jDate: '2019-5-10 15:33:06',
      },
      listData: [
        {
          time: '2023-08-31 16:16',
          type: '1',
        },
        {
          time: '2023-08-29 16:16',
          type: '2',
        },
        {
          time: '2023-08-30 16:16',
          type: '3',
        },
      ],
      sessionNoteData: [],
      generatedContentList: [],
      timeListLeft: [],
      ifEmpty: true,
      machinery: false,
      evenListData: [],
      listData2: {},
      timeListStr: '',
    }
  },
  created() {},
  computed: {},
  watch: {
    //监听路由地址的改变
    $route: {
      immediate: true,
      handler() {
        let path = this.$route.fullPath
        console.log('path', path)
        let paths = path.split('/');
        let routePath = paths[paths.length - 1]
        console.log('routePath', routePath)
        if(routePath === 'TransLate'){
          this.workPlanNum = '5'
        }else if(routePath === 'WorkPlanReprt'){
          this.workPlanNum = '2'
        }
        
        this.timeIndex = 0
        this.workPlanList()
      },
    },
  },

  mounted() {
    this.$nextTick(function () {
      this.screenWidth = window.innerWidth
      this.screenHeight = window.innerHeight
      this.screenHeightBg = this.screenHeight - 152 + 'px'
      // this.workPlanList()
      document.addEventListener('scroll', this.handleScroll, true)
    })
  },
  beforeDestroy() {
    document.removeEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    ...mapGetters(['userInfo']),
    handleScroll(e) {
      var that = this
      const winHeight = e.target.scrollTop || document.documentElement.scrollTop
      // const divSetTop = that.$refs.claims.offsetTop
      // console.log(winHeight)
      if (winHeight >= 71) {
        that.isMobileCont = true
      } else {
        that.isMobileCont = false
      }
    },
    scrollUp() {
      document.body.scrollTop = document.documentElement.scrollTop = 0
    },
    openMobileMode() {
      this.isActive = true
    },
    modalFormOk() {},
    // 修改时间
    editIcon(data) {
      console.log('data', data)
      this.editTime = data.name
      this.iconShow = false
    },
    edit(data, index) {
      let obj = {
        name: this.editTime,
        id: data.id,
      }
      this.$http
        .post('/aiapp/sessionNote/edit', obj)
        .then((res) => {
          console.log('res', res)
          // this.workPlanList()
          if (res.success) {
            this.timeListLeft[index].name = this.editTime
            this.iconShow = true
          }
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    deleteTime(data, index) {
      let obj = {
        templateCode: this.workPlanNum,
        id: data.id,
      }

      deleteAction('/aiapp/sessionNote/delete', obj).then((res) => {
        if (res.success) {
          this.timeListLeft.splice(index, 1)
          if (this.timeListLeft.length === 0) {
            this.workPlanList()
          } else {
            this.timeIndex = 0
            this.choseTime(this.timeListLeft[0], 0)
            this.$message.success('删除成功')
          }
        }
      })
    },
    closeEdit() {
      this.iconShow = true
    },
    // 选择统计图类别
    callback(key) {
      console.log('key', key)
      this.model = this.evenListData[key]
      this.$refs.modalPlanCent.models = this.model
    },
    //处理数据
    evenList(meg) {
      let list = meg
      let key = 'sessionType'
      let key1 = 'createTime'
      var keysArr = list.map((item) => item[key])
      var keys = [...new Set(keysArr)]
      var newList = keys.map((item) => {
        return {
          [key]: item,
          [key1]: list.filter((i) => i[key] == item)[0].createTime,
          list: list.filter((i) => i[key] == item),
        }
      })
      // var array = newList.length === 0 ? this.newList : newList
      var array = newList
      console.log('array', array)
      this.model = array[0].list[0] //中间数据
      this.$refs.modalPlanCent.models = this.model
      this.evenListData = array[0].list //右边数据
    },
    workPlanList() {
      let obj = {
        type: this.workPlanNum,
        userId: this.userInfo().id,
      }

      sessionNoteList(obj).then((res) => {
        console.log('res', res)
        let data = res.result
        this.sessionNoteData = data
        this.timeListLeft = data.reverse()
        if (res.result.length === 0) {
          this.sessionNoteAdd()
        } else {
          this.appApiList()
        }
      })
    },
    sessionNoteAdd() {
      let obj = {
        type: this.workPlanNum,
        userId: this.userInfo().id,
      }
      this.$http
        .post('/aiapp/sessionNote/add', obj)
        .then((res) => {
          console.log('res', res)
          this.workPlanList()
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    appApiList() {
      let obj = {
        templateCode: this.workPlanNum,
        sessionType: this.sessionNoteData[this.timeIndex].id,
      }
      this.$http
        .post('/app/api/list', obj)
        .then((res) => {
          console.log('/app/api/list', res)
          let data = res.result
          this.timeListStr = this.timeListLeft[this.timeIndex].name
          if (data.length === 0) {
            this.model = {}
            this.$refs.modalPlanCent.models = this.model
            this.evenListData = []
            this.ifEmpty = true
            console.log('timeListLeft', this.timeListLeft)
          } else {
            this.generatedContentList = data.reverse()
            if (this.generatedContentList.length >= 1) {
              this.ifEmpty = false
              this.evenList(this.generatedContentList)
              this.$store.dispatch('userLimitList', {userId:this.userInfo().id})
            }
          }
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    textareaTo(str) {
      if (str !== undefined) {
        let regs = new RegExp('\r', 'g')
        let reg = new RegExp('\n', 'g')
        let regSpace = new RegExp(' ', 'g')
        str = str.replace(reg, '<br/>')
        str = str.replace(regs, '<br/>')
        str = str.replace(regSpace, '&nbsp;')
        // console.log('str',str)
        return str
      }
    },
    choseTime(item, index) {
      console.log('index', item, index)
      this.timeIndex = index
      if(this.timeIndex === index){
        return
      }
      this.appApiList()
    },
    addNews() {
      this.sessionNoteAdd()
      // let obj = {
      //   createTime: this.currentTime(),
      //   answer:'',
      // }
      // this.generatedContentList.unshift(obj)
      this.timeIndex = 0
      this.model = {}
      this.evenListData = []

      this.timeIndex = 0
    },
    generatedBtn() {
      this.model = this.$refs.modalPlanCent.models
      this.loadingShow = false
      this.machinery = true
      this.model.id = ''
      console.log('obj', this.model)
      this.$refs.modalPlanCent.generatedBtnProp()

      // this.$refs.form.validate(valid => {
      //     if (valid) {
      //       this.$http
      //         .post('/app/api/ask', obj)
      //         .then((res) => {
      //           console.log('res', res)
      //           this.loadingShow = true
      //           this.appApiList()

      //         })
      //         .catch((error) => {
      //           console.log('error', error)
      //         })
      //     }else{
      //         this.loadingShow = true
      //         this.$message.warning('请填写必填项!')

      //     }
      //   })
    },
    appApiAsk(index,models) {
      console.log('index',index)
      if (index === 2) {
        this.loadingShow = true
        this.machinery = false
        this.$message.warning('请填写必填项!')
      } else {
        this.ifEmpty = true
        // let obj = {
        //   // sessionType: this.timeListLeft[this.timeIndex].id,
        //   // templateCode: this.workPlanNum,
        //   // content: this.model.content,
        //   // dateType: this.model.dateType,
        //   // writeRequired: this.model.writeRequired,
        //   // wordNumber: this.model.wordNumber,
        // }
        models.sessionType = this.timeListLeft[this.timeIndex].id
        models.templateCode = this.workPlanNum
        models.content = this.model.content
        this.$http
          .post('/app/api/ask', models)
          .then((res) => {
            console.log('res', res)
            if(res.code === 500){
            this.$notification.warn({
              message: '提示',
              description: res.message,
              duration:5
            });
            this.memberShow = true
            this.loadingShow = true
            this.machinery = false
          } else if(res.code === 501) {
              this.$notification.warn({
                message: '提示',
                description: res.message,
                duration: 5,
              })
              this.imgShowBool = true
              this.imgLoading = false
            }else{
            if(res.success){
              this.loadingShow = true
              this.machinery = false
              this.appApiList()
            }else{
              this.$message.error('操作失败，请联系管理员！')
            }
          }

            
          })
          .catch((error) => {
            console.log('error', error)
          })
      }
    },
   
  },
}
</script>

<style lang="less">
.justify-between {
  .sheCot {
    width: 48%;
    line-height: 27px;
    color: #fff;
    background: linear-gradient(90deg, #938bff, #ff97f2);
    border-color: #938bff;
    display: inline-block;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    transition: 0.1s;
    font-weight: 500;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    &.copy {
      background: white;
      color: black;
      border: 1px solid #dcdfe6;
      padding: 6px 6px;
      width: 150px;
      margin-left: 20px;
    }
    &.copyTrans{
      padding: 6px 6px;
      width: 150px;
      margin-left: 20px;
    }
  }
  .sheCot:hover {
    opacity: 0.7;
  }
}

.AllOne {
  .ant-form-item {
    float: left;
    width: 100%;
  }
  .ant-form-item-label {
    float: left;
    width: 100%;
    text-align: left;
    font-size: 14px;
    font-weight: 600;
    color: #414141;
  }
  .ant-form-item-control-wrapper {
    .ant-form-item-control {
      height: 40px;
      line-height: 40px;
    }
  }
  textarea {
    width: 100%;
    float: left;
  }
  .ant-col-sm-12 {
    width: 100%;
  }
  input {
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
  }
  .ant-select-selection--single {
    height: 40px;
    line-height: 40px;
  }
  .ant-select-selection__rendered {
    line-height: 39px;
  }
  .btnBoTm {
    float: left;
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 10px;
  }
  .ant-form-item-with-help {
    margin-bottom: 24px;
  }
}
.timeList {
  h6 {
    font-size: 14px;
    font-weight: bold;
    margin-top: 9px;
  }
  .empty {
    text-align: center;
    padding-bottom: 20px;
    img {
      width: 50%;
    }
    .empty-title {
      font-size: 18px;
      font-weight: 500;
      color: #8cbbff;
      margin-top: 15px;
    }
    .empty-content {
      font-size: 14px;
      font-weight: 500;
      color: #8cbbff;
      margin-top: 10px;
    }
  }
  .transCont{
    display: flex;
    align-items: center;
    float: left;
    width: 100%;
    margin-top: 10px;
    .transLeft,.transRight{
      flex: 1;
    }
    .transMid{
      width: 70px;
      cursor: pointer;
      text-align: center;
      i{
        font-size: 30px;
        color: #938bff;
      }
    }
    .transHtml{
      width: 506.48px;
    height: 450px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    transition: all 0.3s, height 0s;
    background: #ff97f224;
    padding: 4px 11px;
    &.load{
      display: flex;
    }
    }
    .transHtml:hover{
      border: 1px solid #1890FF;
    }
  }
}
.result-module {
  padding: 16px 20px 16px;
  border-radius: 8px;
  background: #f7f7f7;
  cursor: pointer;
  .module-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    img {
      width: 60px;
      margin-right: 10px;
    }
  }
  .result-content {
    .result-text {
      margin-top: 20px;
      font-size: 16px;
      color: black;
    }
    .result-time {
      font-size: 14px;
      margin-top: 20px;
    }
  }
}

.loading {
  width: 22px;
  height: 22px;
  border: 2px solid #1890ff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 0.75s linear infinite;
  float: right;
  margin-left: 4px;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

.ant-form-item-children  {
  .editIconMore{
    display: flex;
    align-items: center;
  }
  .addIcon,.shuInput{
    width: 100px;
    text-align: center;
    margin-left: 5px;
    height: 40px;
    line-height: 40px;
    background-color: #938bff;
    border-color: #938bff;
    border-radius: 4px;
    cursor: pointer;
    color: white;
  }
  .shuInput{
    background-color: white;
    border: 1px solid #d9d9d9;
    color:black;
  }
}

.editIconMore{
  .ant-select-selection--multiple{
    .ant-select-selection__choice{
      background-color: #ff97f2;
      color: white;
      .ant-select-remove-icon{
        color: white;
      }
    }
  }
}
 
</style>